﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace wxtools
{
    /// <summary>
    /// 微信登录窗体
    /// </summary>
    public partial class frmLogin : Form
    {
        private WxUtils wxutils = new WxUtils();
        private frmMain frmMain = new frmMain();
        public frmLogin()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picClose_Click(object sender, EventArgs e)
        {
            Close();
        }
        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmLogin_Load(object sender, EventArgs e)
        {
            DoLogin();
            System.Threading.Thread th = new System.Threading.Thread(syncThread);
            th.IsBackground = true;
            th.Start();
        }


        private void syncThread()
        {
            while (!WxConfig.isLogin)
            {
                System.Threading.Thread.Sleep(600);
                checkQrcode();
            }
        }


        /// <summary>
        /// 返回二维码界面 重新加载二维码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkReturn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            linkReturn.Visible = false;
            DoLogin();
        }


        /// <summary>
        /// 登录相关逻辑
        /// </summary>
        private void DoLogin()
        {
            picQRCode.Image = null;
            picQRCode.SizeMode = PictureBoxSizeMode.Zoom;
            lblTip.Text = "手机微信扫一扫以登录";
            string url = "https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=" + WxTools.GetTimeStamp(DateTime.Now);
            string html = WxTools.HttpGet(url, "");
            //window.QRLogin.code = 200; window.QRLogin.uuid = "AZ4OWTeelA==";
            Regex reg = new Regex("window.QRLogin.code = (\\d+); window.QRLogin.uuid = \"(.*?)\"");
            Match mc = reg.Match(html);
            if (mc.Success && mc.Groups.Count == 3 && mc.Groups[1].Value == "200")
            {
                WxConfig.uuid = mc.Groups[2].Value;
                string picurl = string.Format("https://login.weixin.qq.com/qrcode/{0}?t=webwx", WxConfig.uuid);
                byte[] base64_image_bytes = WxTools.HttpGetBytes(picurl);
                MemoryStream memoryStream = new MemoryStream(base64_image_bytes, 0, base64_image_bytes.Length);
                memoryStream.Write(base64_image_bytes, 0, base64_image_bytes.Length);
                //转成图片
                this.Invoke(new MethodInvoker(delegate
                {
                    picQRCode.Image = Image.FromStream(memoryStream);
                    picQRCode.Update();
                }));
                memoryStream.Close();
            }
        }

        private void checkQrcode()
        {
            string url = string.Format("https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=1&_={1}", WxConfig.uuid, WxTools.GetTimeStamp(DateTime.Now));
            string html = WxTools.HttpGet(url, "");
            Regex reg = new Regex("window.code=(\\d+);");
            Match mc = reg.Match(html);
            //txtLoger.Text += html + "\r\n";
            if (mc.Success && mc.Groups.Count == 2 && mc.Groups[1].Value == "201")
            {
                string base64_image = html.Split(new string[] { "\'" }, StringSplitOptions.None)[1].Split(',')[1];
                byte[] base64_image_bytes = Convert.FromBase64String(base64_image);
                MemoryStream memoryStream = new MemoryStream(base64_image_bytes, 0, base64_image_bytes.Length);
                memoryStream.Write(base64_image_bytes, 0, base64_image_bytes.Length);
                //转成图片
                this.Invoke(new MethodInvoker(delegate
                {
                    linkReturn.Visible = true;
                    picQRCode.Image = Image.FromStream(memoryStream);
                }));
                memoryStream.Close();
                //window.userAvatar = 'data
            }
            if (mc.Success && mc.Groups.Count == 2 && (mc.Groups[1].Value == "408" || mc.Groups[1].Value == "0"))
            {
                DoLogin();
            }
            else if (mc.Success && mc.Groups.Count == 2 && mc.Groups[1].Value == "200")
            {
                mc = new Regex("window.redirect_uri=\"(\\S+?)\";").Match(html);
                //txtLoger.Text += "登陆成功,window.redirect_uri:" + mc.Groups[1].Value + "\r\n";
                WxConfig.redirect_uri = mc.Groups[1].Value + "&fun=new";
                WxConfig.base_uri = WxConfig.redirect_uri.Substring(0, WxConfig.redirect_uri.LastIndexOf("/"));
                //https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=03f725a8039d418ab79c69b6ffbd771b&lang=zh_CN&scan=1388975896&fun=new
                var services = new List<string[]>(){
                    new string[2]{"wx2.qq.com", "webpush2.weixin.qq.com"},  
                    new string[2]{"qq.com", "webpush.weixin.qq.com"},  
                    new string[2]{"web1.wechat.com", "webpush1.wechat.com"},  
                    new string[2]{"web2.wechat.com", "webpush2.wechat.com"},  
                    new string[2]{"wechat.com", "webpush.wechat.com"},  
                    new string[2]{"web1.wechatapp.com", "webpush1.wechatapp.com"}
                };
                WxConfig.push_uri = WxConfig.base_uri;
                foreach (string[] item in services)
                {
                    if (WxConfig.base_uri.IndexOf(item[0]) >= 0)
                    {
                        WxConfig.push_uri = string.Format("https://{0}/cgi-bin/mmwebwx-bin", item[1]);
                        break;
                    }
                }
                //txtLoger.Text += "登陆成功,push_uri:" + WxConfig.push_uri + "\r\n";

                html = WxTools.HttpGetCookies(WxConfig.redirect_uri, "");
                wxutils.webwxinit(html);
                WxConfig.isLogin = true;
                this.Invoke(new MethodInvoker(delegate
                {
                    frmMain.Show();
                    this.Hide();
                }));
            }
        }
    }
}
